package com.zbcz.crm.viewmodel

import android.content.Context
import android.net.Uri
import android.os.Environment
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModel
import com.zbcz.crm.CrmApplication
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

class MarketManagerViewModel : ViewModel() {
    suspend fun downloadFile(context: Context, fileUrl: String, fileName: String): File? {
        return withContext(Dispatchers.IO) {
            val client = OkHttpClient()
            val request = Request.Builder().url(fileUrl).build()

            try {
                val response = client.newCall(request).execute()
                if (response.isSuccessful) {
                    response.body?.let { body ->
//                        val directory =
//                            CrmApplication.mApplication.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
//                        val file = File(directory, "downloads/$fileName")
                        val dcimDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                        val file = File(dcimDir, "Crm/$fileName") // 保存到DCIM/Crm目录
                        file.parentFile?.mkdirs()
                        val inputStream: InputStream = body.byteStream()
                        val outputStream = FileOutputStream(file)

                        inputStream.use { input ->
                            outputStream.use { output ->
                                input.copyTo(output)
                            }
                        }
//                        return@withContext FileProvider.getUriForFile(
//                            context,
//                            "${context.packageName}.provider",
//                            file
//                        )
                        return@withContext file
                    }
                } else {
                    null
                }
            } catch (e: IOException) {
                e.printStackTrace()
                null
            }
        }
    }


    override fun onCleared() {
        super.onCleared()
    }
}